using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using DocumentCreationSystem.Models;
using Microsoft.Win32;

namespace DocumentCreationSystem.Views;

/// <summary>
/// 工具统计对话框
/// </summary>
public partial class ToolStatisticsDialog : Window
{
    private readonly ToolUsageStatistics _statistics;

    public ToolStatisticsDialog(ToolUsageStatistics statistics)
    {
        InitializeComponent();
        
        _statistics = statistics;
        
        InitializeDisplay();
    }

    private void InitializeDisplay()
    {
        // 概览统计
        TotalUsageText.Text = _statistics.TotalUsageCount.ToString("N0");
        TotalTimeText.Text = FormatTimeSpan(_statistics.TotalExecutionTime);
        SuccessRateText.Text = $"{_statistics.SuccessRate:P1}";
        ActiveToolsText.Text = _statistics.ToolUsageCounts.Count(kvp => kvp.Value > 0).ToString();
        
        // 最常用工具
        DisplayMostUsedTools();
        
        // 工具使用详情
        DisplayToolUsageDetails();
        
        // 统计信息
        PeriodText.Text = $"{_statistics.Period.StartTime:yyyy-MM-dd} 至 {_statistics.Period.EndTime:yyyy-MM-dd}";
        ProjectIdText.Text = _statistics.ProjectId.ToString();
        GeneratedAtText.Text = _statistics.GeneratedAt.ToString("yyyy-MM-dd HH:mm:ss");
    }

    private void DisplayMostUsedTools()
    {
        MostUsedToolsListBox.Items.Clear();
        
        foreach (var toolId in _statistics.MostUsedTools)
        {
            if (_statistics.ToolUsageCounts.TryGetValue(toolId, out var count))
            {
                var item = new ListBoxItem();
                var grid = new Grid();
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
                
                var toolText = new TextBlock
                {
                    Text = GetToolDisplayName(toolId),
                    VerticalAlignment = VerticalAlignment.Center
                };
                Grid.SetColumn(toolText, 0);
                grid.Children.Add(toolText);
                
                var countText = new TextBlock
                {
                    Text = count.ToString("N0"),
                    FontWeight = FontWeights.Bold,
                    Foreground = (System.Windows.Media.Brush)FindResource("PrimaryHueMidBrush"),
                    VerticalAlignment = VerticalAlignment.Center
                };
                Grid.SetColumn(countText, 1);
                grid.Children.Add(countText);
                
                item.Content = grid;
                MostUsedToolsListBox.Items.Add(item);
            }
        }
    }

    private void DisplayToolUsageDetails()
    {
        var toolDetails = new List<ToolUsageDetail>();
        
        foreach (var kvp in _statistics.ToolUsageCounts.OrderByDescending(x => x.Value))
        {
            var toolId = kvp.Key;
            var usageCount = kvp.Value;
            
            var totalTime = _statistics.ToolExecutionTimes.GetValueOrDefault(toolId, TimeSpan.Zero);
            var averageTime = usageCount > 0 ? TimeSpan.FromMilliseconds(totalTime.TotalMilliseconds / usageCount) : TimeSpan.Zero;
            
            toolDetails.Add(new ToolUsageDetail
            {
                ToolId = GetToolDisplayName(toolId),
                UsageCount = usageCount,
                TotalTime = FormatTimeSpan(totalTime),
                AverageTime = FormatTimeSpan(averageTime),
                LastUsed = "N/A" // 简化实现
            });
        }
        
        ToolUsageDataGrid.ItemsSource = toolDetails;
    }

    private string GetToolDisplayName(string toolId)
    {
        // 简化的工具名称映射
        return toolId switch
        {
            "batch-format-converter" => "批量格式转换",
            "ai-content-generator" => "AI内容生成器",
            "content-analyzer" => "内容分析器",
            "project-backup" => "项目备份",
            "quality-checker" => "质量检查器",
            _ => toolId
        };
    }

    private string FormatTimeSpan(TimeSpan timeSpan)
    {
        if (timeSpan.TotalDays >= 1)
            return $"{timeSpan.TotalDays:F1}天";
        if (timeSpan.TotalHours >= 1)
            return $"{timeSpan.TotalHours:F1}小时";
        if (timeSpan.TotalMinutes >= 1)
            return $"{timeSpan.TotalMinutes:F1}分钟";
        if (timeSpan.TotalSeconds >= 1)
            return $"{timeSpan.TotalSeconds:F1}秒";
        
        return $"{timeSpan.TotalMilliseconds:F0}ms";
    }

    private void ExportStatistics_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var saveDialog = new SaveFileDialog
            {
                Title = "导出工具统计",
                Filter = "JSON文件 (*.json)|*.json|CSV文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
                DefaultExt = "json",
                FileName = $"ToolStatistics_{DateTime.Now:yyyyMMdd_HHmmss}"
            };
            
            if (saveDialog.ShowDialog() == true)
            {
                var extension = Path.GetExtension(saveDialog.FileName).ToLower();
                
                if (extension == ".csv")
                {
                    ExportToCsv(saveDialog.FileName);
                }
                else
                {
                    ExportToJson(saveDialog.FileName);
                }
                
                MessageBox.Show($"统计数据已导出到: {saveDialog.FileName}", "导出成功", 
                              MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ExportToJson(string fileName)
    {
        var json = JsonSerializer.Serialize(_statistics, new JsonSerializerOptions { WriteIndented = true });
        File.WriteAllText(fileName, json);
    }

    private void ExportToCsv(string fileName)
    {
        var csv = new System.Text.StringBuilder();
        csv.AppendLine("工具ID,使用次数,总执行时间(ms),平均执行时间(ms)");
        
        foreach (var kvp in _statistics.ToolUsageCounts)
        {
            var toolId = kvp.Key;
            var usageCount = kvp.Value;
            var totalTime = _statistics.ToolExecutionTimes.GetValueOrDefault(toolId, TimeSpan.Zero);
            var averageTime = usageCount > 0 ? totalTime.TotalMilliseconds / usageCount : 0;
            
            csv.AppendLine($"{GetToolDisplayName(toolId)},{usageCount},{totalTime.TotalMilliseconds:F0},{averageTime:F0}");
        }
        
        File.WriteAllText(fileName, csv.ToString());
    }

    private void RefreshStatistics_Click(object sender, RoutedEventArgs e)
    {
        // 刷新统计显示
        InitializeDisplay();
    }

    private void Close_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}

/// <summary>
/// 工具使用详情数据模型
/// </summary>
public class ToolUsageDetail
{
    public string ToolId { get; set; } = string.Empty;
    public int UsageCount { get; set; }
    public string TotalTime { get; set; } = string.Empty;
    public string AverageTime { get; set; } = string.Empty;
    public string LastUsed { get; set; } = string.Empty;
}
